package com.xuliugen.image.util;

import java.lang.Thread.State;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import com.xuliugen.image.callbackinter.CallbackImageFresh;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

public class LazyImageLoader {

	private static final int MESSAGE_ID = 1;
	public static final String EXTRA_IMG_URL = "extra_img_url";
	public static final String EXTRA_IMG = "extra_img";

	private static Context context;
	private Activity activity;
	// 创建一个ImageManager对象
	private ImageManager imgManger = null;

	public LazyImageLoader(Context ct, Activity activity) {
		context = ct;
		this.activity = activity;
		imgManger = new ImageManager(context);
	}

	// 阻塞队列：即下载的url队列
	private BlockingQueue<String> urlQueue = new ArrayBlockingQueue<String>(50);

	// 正在下载的线程
	private DownloadImageThread downloadImgThread = new DownloadImageThread();

	/**
	 * 用用户在本地文件中没有找到的时候使用
	 */
	public void lazyImgLoader(String url) {
		startDownLoadTread(url); // 开启线程进行下载
	}

	/**
	 * 开始下载的线程
	 */
	private void startDownLoadTread(String url) {

		putUrlToUrlQueue(url); // 放入到Url队列：即下载队列中

		State state = downloadImgThread.getState();

		if (state == State.NEW) {
			downloadImgThread.start();
		}
		// 线程已经进行介绍
		else if (state == State.TERMINATED) {
			downloadImgThread = new DownloadImageThread();
			downloadImgThread.start();
		}
	}

	/**
	 * 将url添加到Url队列中
	 * 
	 * @param url
	 */
	private void putUrlToUrlQueue(String url) {

		if (!urlQueue.contains(url)) {
			try {
				urlQueue.put(url);

			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {

			case MESSAGE_ID: {

				Bundle bundle = msg.getData();

				Bitmap bitmap = bundle.getParcelable(EXTRA_IMG);

				// 刷新UI:要传入一个Activity
				CallbackImageFresh callbackImageFresh = (CallbackImageFresh) activity;
				callbackImageFresh.fresh(bitmap); // 调用回调函数

				break;
			}
			}
		};
	};

	/**
	 * 下载Image的Thread
	 */
	private class DownloadImageThread extends Thread {

		private boolean isRun = true;

		public void shutDown() {
			isRun = false;
		}

		public void run() {
			try {
				while (isRun) {
					String url = urlQueue.poll();
					if (null == url) {
						break;
					}
					//首先从本地获取
					//Bitmap bitmap = ImageManager.defualtImage; // 为bitmap设置一个默认的图片
					Bitmap bitmap = null;
					if (imgManger.contains(url)) { // 如果在Cache中存在
						bitmap = imgManger.getFromLocal(url); // 从cache中获取
						System.out.println("--------------  我是从本次缓存中获取的！");
					}
					if(bitmap == null){
						//这里才是真正的进行下载操作
						bitmap = imgManger.safeGet(url);
						System.out.println("--------------  我是从网络下载后获取的！");
					}
					
					Message msg = handler.obtainMessage(MESSAGE_ID);
					Bundle bundle = msg.getData();
					// bundle.putSerializable(EXTRA_IMG_URL, url);
					bundle.putParcelable(EXTRA_IMG, bitmap);

					handler.sendMessage(msg);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				shutDown();
			}
		}
	}
}
